// pages/checkin/checkin.js
const app = getApp()

Page({
  data: {
    formData: {
      item_name: '',
      item_category: '',
      item_description: '',
      item_reason: '',
      item_image: ''
    },
    categories: [
      '衣物鞋帽', '书籍文件', '数码产品', '家居用品', 
      '美妆护肤', '食品饮料', '运动器材', '其他'
    ],
    isSubmitting: false,
    todayCheckIn: null
  },

  onLoad() {
    this.loadTodayCheckIn()
  },

  // 加载今日打卡状态
  loadTodayCheckIn() {
    app.request('/checkin/today', 'GET')
      .then(res => {
        this.setData({
          todayCheckIn: res.data
        })
        if (res.data) {
          this.setData({
            formData: {
              item_name: res.data.item_name,
              item_category: res.data.item_category,
              item_description: res.data.item_description,
              item_reason: res.data.item_reason,
              item_image: res.data.item_image
            }
          })
        }
      })
      .catch(err => {
        console.error('加载今日打卡状态失败:', err)
      })
  },

  // 输入框变化
  onInputChange(e) {
    const field = e.currentTarget.dataset.field
    const value = e.detail.value
    this.setData({
      [`formData.${field}`]: value
    })
  },

  // 选择分类
  onCategoryChange(e) {
    const index = e.detail.value
    this.setData({
      'formData.item_category': this.data.categories[index]
    })
  },

  // 选择图片
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        this.uploadImage(tempFilePath)
      }
    })
  },

  // 上传图片
  uploadImage(filePath) {
    wx.uploadFile({
      url: `${app.globalData.baseURL}/upload`,
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        const data = JSON.parse(res.data)
        if (data.code === 200) {
          this.setData({
            'formData.item_image': data.data.url
          })
          wx.showToast({
            title: '上传成功',
            icon: 'success'
          })
        }
      },
      fail: (err) => {
        wx.showToast({
          title: '上传失败',
          icon: 'error'
        })
      }
    })
  },

  // 删除图片
  deleteImage() {
    this.setData({
      'formData.item_image': ''
    })
  },

  // 表单验证
  validateForm() {
    if (!this.data.formData.item_name.trim()) {
      wx.showToast({
        title: '请输入物品名称',
        icon: 'none'
      })
      return false
    }
    return true
  },

  // 提交打卡
  submitCheckIn() {
    if (!this.validateForm()) return

    this.setData({ isSubmitting: true })

    const url = this.data.todayCheckIn ? 
      `/checkin/${this.data.todayCheckIn.id}` : 
      '/checkin'
    
    const method = this.data.todayCheckIn ? 'PUT' : 'POST'

    app.request(url, method, this.data.formData)
      .then(res => {
        wx.showToast({
          title: this.data.todayCheckIn ? '更新成功' : '打卡成功',
          icon: 'success'
        })
        
        // 更新用户信息
        app.getUserInfo()
        
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      })
      .catch(err => {
        wx.showToast({
          title: '操作失败',
          icon: 'error'
        })
      })
      .finally(() => {
        this.setData({ isSubmitting: false })
      })
  },

  // 重置表单
  resetForm() {
    this.setData({
      formData: {
        item_name: '',
        item_category: '',
        item_description: '',
        item_reason: '',
        item_image: ''
      }
    })
  }
})